package com.cpi.basilos.user.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.util.MessageResources;

import com.cpi.basilos.user.exception.UserException;
import com.cpi.basilos.user.form.UserForm;
import com.cpi.basilos.user.service.UserService;
import com.cpi.user.view.UserView;
import com.cs.common.exception.CSException;
import com.cs.common.struts.Actionable;

public class UserAction extends MappingDispatchAction implements Actionable{
	public ActionForward login(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws UserException {
		UserService userService = null;
		UserForm userForm = null;
		UserView userView = null;
		MessageResources messageResources = null;
		String messageError = null;
		String forward = null;
		HttpSession httpSession = null;
		try{
			httpSession = request.getSession();
			userService = new UserService();
			userForm = (UserForm) form;
			messageResources = getResources(request);
			userView = userForm.getUserView();
			userService.loginUser(userView);
			httpSession.setAttribute(USER_SESSION_NAME, userView);
			forward = SUCCESS;
		}catch(UserException userException){
			messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), userException.getErrorCode());
			if(null == messageError){
				httpSession.setAttribute(CUSTOM_EXCEPTION, userException);
				form.reset(mapping, request);
				throw userException;
			}else{
				httpSession.setAttribute(ERROR_MESSAGE, messageError);
				forward = FAILS;
			}
		}catch(Exception exception){
			UserException userException = null;
			exception.printStackTrace(System.out);
			userException = new UserException(exception , CSException.LAYER_ACTION,CSException.ACTION_LOGIN);
			form.reset(mapping, request);
			httpSession.setAttribute(CUSTOM_EXCEPTION, userException);
			throw userException;
		}
		return mapping.findForward(forward);
	}
	
	public ActionForward logout(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws UserException {
		HttpSession httpSession = null;
		try{
			httpSession = request.getSession();
			httpSession.invalidate();
		}catch(Exception exception){
			UserException userException = null;
			exception.printStackTrace(System.out);
			userException = new UserException(exception , CSException.LAYER_ACTION, CSException.ACTION_LOGIN);
			throw userException;
		}finally{
			httpSession = null;
		}
		return mapping.findForward(DEFAULT_FORWARD);
	}
}
